using System;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;

using ctsu.Admin.Forms;
using NLog;

namespace ctsu.Admin.Forms
{
	public partial class LoginForm : Form
	{
        private static Logger _logger = LogManager.GetCurrentClassLogger();

		public FormMain _frmMain;
		public static GenericIdentity UserIdentity;
		public static ctsu.Security.AppSecurity ApplicationSecurity;
		private int _tryCount;

		public LoginForm()
		{
			InitializeComponent();

		}

		private void LoginForm_Load(object sender, EventArgs e)
		{
			//throw new Exception("Test");
			this.Left = Utils.GetLeftCenterCoord(this.Width);
			this.Top = 25;

			ApplicationSecurity = new Security.AppSecurity();
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btnOK_Click(object sender, EventArgs e)
		{
			_tryCount++;
			StringBuilder sb = new StringBuilder();

			Cursor.Current = Cursors.WaitCursor;
			try
			{
				ApplicationSecurity.VerifyUser(txtUid.Text, txtPw.Text);
				if (ApplicationSecurity.ApplicationUser.IsAuthenticated)
				{

					Cursor.Current = Cursors.WaitCursor;
					Console.WriteLine("Before creating fromMain instance");
					_frmMain = new FormMain();
					_frmMain.Closed += new System.EventHandler(this.MainForm_Closed);
					Console.WriteLine("Before showing fromMain instance");
					this.Hide();
					_frmMain.Show();
					Console.WriteLine("After showing fromMain instance");
                    _logger.Info("Login - user: " + txtUid.Text);
					_frmMain.LoadForms();
				}
				else
				{
					sb.Append("Access Denied");
					MessageBox.Show(this, sb.ToString(), "Access Denied",
						MessageBoxButtons.OK, MessageBoxIcon.Stop);
				}

				if ((_tryCount == 3) && (ApplicationSecurity.ApplicationUser.IsAuthenticated == false))
				{
					sb.Remove(0, sb.Length);
					sb.Append("This is the third failed login attempt.");
					sb.Append(Environment.NewLine);
					sb.Append("The program will now shut down.");
					MessageBox.Show(this, sb.ToString(), "Access Denied",
						MessageBoxButtons.OK, MessageBoxIcon.Stop);
					this.Close();
				}
			}
			catch (Exception ex)
			{
				////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, "Error starting Crema2:" + ex.Message, "Crema2 Error");
			}

		}

		private void MainForm_Closed(object sender, System.EventArgs e)
		{
			this.Close();
		}

	}

}